from rest_framework.views import APIView
from django.utils import timezone
from tensquare.utils.image_check import image_checking
from tensquare.utils.qiniu_upload import QiNiu
from tensquare.utils.fast_dfs import FastDFSStorage
from rest_framework.response import Response
from django.http import HttpResponseRedirect


class UploadUserProfile(APIView):
    """ 用户上传头像 """

    # 七牛云上传
    def post(self, request):
        user_id = request.user.id
        image_file = self.request.data.get('img')

        if image_checking(image_file) is None:
            return Response({'errno': 400, 'errmsg': '上传文件不是图片'})

        image_byte = image_file.read()
        avatar = 'tensuqare/user/avatar/' + str(user_id) + '/' + timezone.localtime().strftime('%Y%m%d%H%M%S')
        url = QiNiu().upload_data(avatar, image_byte)

        return Response({'imgurl': url}, status=201)

    # FastDFS上传
    def post(self, request):
        image_file = self.request.data.get("img")   # 文件对象
        if image_checking(image_file) is None:
            return Response({'errno': 400, 'errmsg': '上传文件不是图片'})

        image = FastDFSStorage()._save(name=None, file=image_file)
        url = image.url

        return Response({"img": url}, status=201)


class UploadImage(APIView):
    """ 富文本编辑器上传图片 """

    # 七牛云上传
    def post(self, request):
        image_file = self.request.data.get("upload")    # 文件对象
        if image_checking(image_file) is None:
            return Response({'errno': 400, 'errmsg': '上传文件不是图片'})

        image_byte = image_file.read()
        avatar = 'tensuqare/text/image/' + timezone.localtime().strftime('%Y%m%d%H%M%S')
        url = QiNiu().upload_data(avatar, image_byte)
        head = 'http://www.tensquare.site/upload_success.html?'

        return HttpResponseRedirect(head + url)

    # FastDFS上传
    def post(self, request):
        image_file = self.request.data.get("upload")    # 文件对象
        if image_checking(image_file) is None:
            return Response({'errno': 400, 'errmsg': '上传文件不是图片'})

        image = FastDFSStorage()._save(name=None, file=image_file)
        url = image.url
        head = 'http://www.tensquare.site/upload_success.html?'

        return HttpResponseRedirect(head + url)
